var app = getApp()
import _config from '../../utils/config';
import _fetch from '../../utils/httpService';
import util from '../../utils/util';

Page({
  data: {
    tab: 0,
    order: {
      title: '',
      linker: '',
      linkerPhone: '',
      adress: '',
      detailAdress: '',
      orderStatus: '',
      orderNo: '',
      appointment: '',
      project: '',
      desc: ''
    },
    orderList: [],
    addressInfo: {},
    cancelInfo: {},
    dealShow: false,
    statusList: [
      '',
      '待受理',
      '待指派',
      '待接单',
      '待服务',
      '服务中',
      '已完成',
      '已取消'
    ],
    templateName: '',
    logFlow: [],
    serve: {
      avatar: '',
      name: '',
      phone: '',
      serveFlow: []
    },
    applyShow: false,
    applyDesc: '',
    checkRadio: '1',
    radioGroup: [{
      value: '1',
      name: '申请取消',
    }, {
      value: '2',
      name: '申请改派',
    }],
    buttonList: [],
    perms: {
      accept: '受理工单',
      refuse: '拒绝工单',
      assignForm: '指派人员',
      // transferForm: '转派团队', 2期
      grabForm: '抢单',
      receiveForm: '接受工单',
      refuseForm: '拒绝工单',
      startService: '开始服务',
      applyException: '申请异常',
      writeProgress: '填写进度',
      completeService: '完成服务',
      agreeApply: '同意',
      rejectApply: '驳回',
      // formMessage: '工单留言', 2期
      cancelForm: '取消工单',
      // evaluateForm: '评价工单', 2期
    },
    permsList: {
      permsButton: [],
      hoverShow: false,
      hoverItems: []
    },
    formId: null,
    formAbId: null,
    teamId: null,
    canRefuse: false,
    canAccept: false,
    applyLocationShow: false,
    phoneCall: {
      phoneCallShow: false,
      phoneNum: null,
      customerName: null
    },
    cancelShow: false,
    cancelReason: '',
    reasonText: ''
  },
  onLoad: function (options) {
    // 生命周期函数--监听页面加载
    let formId = options.id
    this.setData({
      formId: options.id,
      formAbId: options.fid || null
    })
    this.getDetail(formId)
    this.getOrderlog(formId)
    this.getProgress(formId)
    wx.setNavigationBarTitle({
      title: '工单详情'
    })
    getApp().globalData.formId = null
    getApp().globalData.formAbId = null
  },
  onReady: function () {
    // 生命周期函数--监听页面初次渲染完成

  },
  onShow: function () {
    // 生命周期函数--监听页面显示
    this.getDetail(this.data.formId)
    this.getOrderlog(this.data.formId)
    this.getProgress(this.data.formId)

  },
  onHide: function () {
    // 生命周期函数--监听页面隐藏

  },
  onUnload: function () {
    // 生命周期函数--监听页面卸载

  },
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作

  },
  onReachBottom: function () {
    // 页面上拉触底事件的处理函数

  },
  onShareAppMessage: function () {
    // 用户点击右上角分享
    return {
      title: '助力企业工单管理智能升级', // 分享标题
      desc: '', // 分享描述
      path: '/pages/login/index', // 分享路径
      imageUrl: '../../img/Mask.png' // 分享图片
    }
  },
  getProgress(id) {
    // 获取工单进度
    let vm = this
    let url = _config.url.get_progress_list.replace('{formId}', id);
    _fetch.get(url).then(function (data) {
      let arr = [],
        curIndex = null,
        flag = true
      if (data.reportList && data.reportList.length > 0) {
        data.reportList.map((i, index) => {
          if (i.isCurrent) {
            flag = false
            if (i.isCurrent === 1) {
              curIndex = index
            } else {
              if (data.reportList.length === 1) {
                i.isDone = true
              }
            }
          }
        })
        arr = data.reportList.map((v, idx) => {
          if (v.isCurrent && v.isCurrent === 1) {
            v.isActive = true
          }
          if (flag) {
            v.isDone = true
          } else {
            if (idx < curIndex) {
              v.isDone = true
            }
          }
          let jtemp = []
          if (v.reportItemList && v.reportItemList.length) {
            jtemp = v.reportItemList.map(j => {
              j.showText = j.componentValue
              if ((j.componentType === 4 || j.componentType === 8) && j.componentValue) {
                if (j.componentType === 8) {
                  let address = JSON.parse(j.componentValue)
                  if (address.addressType === 1) {
                    j.showText = address.addressValue.provinceName + address.addressValue.cityName + address.addressValue.areaName
                  } else {
                    j.showText = address.addressValue.location
                  }
                } else {
                  j.showText = JSON.parse(j.componentValue)
                }
              }
              if (j.componentType === 6 && j.componentValue) {
                j.showText = j.componentValue.split(',')
              }
              if (j.componentType === 7 && j.componentValue) {
                // j.showText = util.formatTime(Number(j.componentValue)).substr(0, 16)
                j.showText = j.componentValue
              }
              return j
            })
          }
          v.reportItemList = jtemp
          return v
        })
      }
      vm.setData({
        'serve.serveFlow': arr,
        'serve.name': data.serviceStaffName,
        'serve.phone': data.serviceStaffPhone,
        'serve.avatar': data.headImg
      })
      wx.hideLoading()
    }).catch(function (error) {
      wx.showToast({
        title: error.msg,
        icon: 'none',
      });
    });
  },
  getOrderlog(id) {
    // 获取工单日志
    let vm = this
    let url = _config.url.get_work_log.replace('{id}', id);
    _fetch.get(url).then(function (data) {
      vm.setData({
        logFlow: data
      })
      wx.hideLoading()
    }).catch(function (error) {
      wx.showToast({
        title: error.msg,
        icon: 'none',
      });
    });
  },
  getDetail(id) {
    // 获取详情
    let vm = this
    let url = _config.url.get_work_detail.replace('{id}', id);
    _fetch.get(url)
      .then(function (data) {
        if (data.dataList && data.dataList.length) {
          let itemp = data.dataList.map(i => {
            let fieldTemp = i.field
            let fieldValue = i.componentValue || ''
            if (i.field.indexOf('_') > -1) {
              let arr = i.field.split('_')
              arr[1] = arr[1].replace(arr[1][0], arr[1][0].toUpperCase())
              fieldTemp = arr[0] + arr[1]
            }
            if (i.field === 'address') {
              let value = JSON.parse(i.componentValue)
              vm.setData({
                addressInfo: value
              })
              fieldValue = value.addressType === 1 ? (value.addressValue.provinceName + value.addressValue.cityName + value.addressValue.areaName) : value.addressValue.location
            }
            i.showText = i.componentValue || ''
            if ((i.componentType === 4 || i.componentType === 8) && i.componentValue) {
              if (i.componentType === 8) {
                let address = JSON.parse(i.componentValue)
                if (address.addressType === 1) {
                  i.showText = address.addressValue.provinceName + address.addressValue.cityName + address.addressValue.areaName
                } else {
                  i.showText = address.addressValue.location
                }
              } else {
                i.showText = JSON.parse(i.componentValue)
              }
            }
            if (i.componentType === 6 && i.componentValue) {
              i.showText = i.componentValue.split(',')
            }
            if (i.componentType === 7 && i.componentValue) {
              i.showText = i.componentValue
            }
            if (i.componentType === 20) {
              if (i.componentValue) {
                let obj = JSON.parse(i.componentValue)
                i.showText = obj.projectName
              }
            }
            if (i.componentType === 22) {
              if (i.componentValue) {
                let obj = JSON.parse(i.componentValue)
                i.showText = obj.customerName
              }
            }
            vm.data.order[fieldTemp] = fieldValue
            return i
          })

          vm.setData({
            formAbId: data.formAbnormalId,
            order: vm.data.order,
            orderList: itemp,
            'order.orderNo': data.orderNo,
            'order.orderStatus': data.orderStatus,
            buttonList: data.buttonList,
            cancelInfo: data.cancelInfo,
            teamId: data.serviceTeamId,
            templateName: data.templateName,
            reasonText: data.cancelInfo ? data.cancelInfo.reason.split('：')[1] : ''
          })
          let permsList = app.globalData.perms
          vm.data.permsList.permsButton = []
          vm.data.permsList.hoverItems = []
          getApp().globalData.writeProgress = false
          if (permsList && vm.data.buttonList && permsList.length > 0 && vm.data.buttonList.length > 0) {
            for (let i = 0; i < permsList.length; i++) {
              for (let j = 0; j < vm.data.buttonList.length; j++) {
                if (permsList[i] !== 'transferForm' && permsList[i] !== 'formMessage' && permsList[i] !==
                  'evaluateForm' && permsList[i] === vm.data.buttonList[j]) {
                  if (permsList[i] === 'agreeApply' || permsList[i] === 'rejectApply') {
                    if (permsList[i] === 'agreeApply') {
                      vm.setData({
                        canAccept: true
                      })
                    } else {
                      vm.setData({
                        canRefuse: true
                      })
                    }
                    vm.data.permsList.permsButton.push({
                      text: '异常处理',
                      perms: permsList[i]
                    })
                  } else {
                    if (permsList[i] === 'writeProgress') {
                      getApp().globalData.writeProgress = true
                    }
                    vm.data.permsList.permsButton.push({
                      text: vm.data.perms[permsList[i]],
                      perms: permsList[i]
                    })
                  }
                }
              }
            }
            // 去重（异常处理-同意-拒绝）
            let hash = {};
            let arr = vm.data.permsList.permsButton;
            arr = arr.reduce(function (item, next) {
              hash[next.text] ?
                "" :
                (hash[next.text] = true && item.push(next));
              return item;
            }, []);
            vm.data.permsList.permsButton = arr
            if (vm.data.permsList.permsButton.length > 2) {
              vm.data.permsList.hoverItems = vm.data.permsList.permsButton.splice(2, vm.data.permsList.permsButton.length - 2)
            }
            vm.setData({
              permsList: vm.data.permsList
            })
          }
          wx.hideLoading()
        }
      }).catch(function (error) {
        wx.showToast({
          title: error.msg,
          icon: 'none',
        });
      });
  },
  // 点击tab事件
  tapTab: function (event) {
    this.setData({
      tab: event.currentTarget.dataset.tab,
    })
  },
  openHover() {
    this.setData({
      'permsList.hoverShow': !this.data.permsList.hoverShow
    })
  },
  settingCallback(res) {
    if (res.detail.authSetting['scope.userLocation']) {
      this.setData({
        applyLocationShow: false
      })
    }
  },
  openMap() {
    let that = this
    wx.getSetting({ //请求授权
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              that.getCurrentLocatin()
            },
            fail() {
              that.setData({
                applyLocationShow: true
              })
            }
          })
        } else {
          that.getCurrentLocatin()
        }
      },
      fail() {
        that.setData({
          applyLocationShow: true
        })
      }
    })
  },
  getCurrentLocatin() {
    //打开地图
    console.log(this.data.addressInfo)
    let that = this
    if (this.data.addressInfo.addressType == 0) {
      wx.getLocation({ //获取当前经纬度
        type: 'wgs84', //返回可以用于wx.openLocation的经纬度，官方提示bug: iOS 6.3.30 type 参数不生效，只会返回 wgs84 类型的坐标信息  
        success: function (res) {
          wx.openLocation({ //​使用微信内置地图查看位置。
            latitude: Number(that.data.addressInfo.addressValue.latitude),
            longitude: Number(that.data.addressInfo.addressValue.longitude),
            name: that.data.addressInfo.addressValue.location,
            address: that.data.addressInfo.addressValue.location
          })
        }
      })
    } else {
      let locationString = this.data.addressInfo.addressValue.provinceName + this.data.addressInfo.addressValue.cityName + this.data.addressInfo.addressValue.areaName
      wx.request({
        url: 'https://apis.map.qq.com/ws/geocoder/v1/',
        data: {
          "key": "3ESBZ-ZLBKK-PGZJ6-APQDW-APKMF-E5FSK",
          "address": locationString
        },
        method: 'GET',
        success: function (data) {
          wx.openLocation({ //​使用微信内置地图查看位置。
            latitude: data.data.result.location.lat,
            longitude: data.data.result.location.lng,
            name: locationString,
            address: locationString
          })
        }
      })
    }
  },
  makePhoneCall() {
    this.setData({
      phoneCall: {
        phoneCallShow: true,
        phoneNum: this.data.order.linkerPhone,
        customerName: this.data.order.linker
      }
    })
  },
  toPhoneCall() {
    // 拨打电话
    let that = this
    wx.makePhoneCall({
      phoneNumber: that.data.order.linkerPhone
    })
  },
  cancelPhone() {
    this.setData({
      phoneCall: {
        phoneCallShow: false,
        phoneNum: null,
        customerName: null
      }
    })
  },
  tabAR(type) {
    // 受理/拒绝工单
    let requestData = {
      acceptStatus: type === 'refuse' ? 0 : 1,
      formIds: [this.data.formId]
    }
    _fetch.put(_config.url.accpet_refuse, requestData).then(() => {
      this.getDetail(this.data.formId)
      this.getOrderlog(this.data.formId)
      this.getProgress(this.data.formId)
      wx.hideLoading()
      wx.showToast({
        title: `${type === 'refuse' ? '拒绝' : '受理'}成功`,
        icon: 'none',
        duration: 2000
      })
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  tapARBOrder(type) {
    // 接/拒/抢单
    let requestData = {
      status: type === 'refuseForm' ? 0 : 1
    }
    let url = type === 'grabForm' ? _config.url.grab_work.replace('{id}', this.data.formId) : _config.url.catch_refuse_work.replace('{id}', this.data.formId)
    _fetch.put(url, type === 'grabForm' ? null : requestData).then(() => {
      this.getDetail(this.data.formId)
      this.getOrderlog(this.data.formId)
      this.getProgress(this.data.formId)
      wx.hideLoading()
      wx.showToast({
        title: `${type === 'grabForm' ? '抢单' : type === 'receiveForm' ? '接单' : '拒绝'}成功`,
        icon: 'none',
        duration: 2000
      })
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  tapService(type) {
    // 开始/完成服务
    let url = type === 'startService' ? _config.url.begin_service : _config.url.server_done
    let requestData = {
      formId: this.data.formId
    }
    _fetch.put(url, requestData).then(() => {
      this.getDetail(this.data.formId)
      this.getOrderlog(this.data.formId)
      this.getProgress(this.data.formId)
      wx.hideLoading()
      wx.showToast({
        title: `${type === 'startService' ? '开始服务' : '服务完成'}成功`,
        icon: 'none',
        duration: 2000
      })
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  closeCancel() {
    this.setData({
      cancelShow: false,
      cancelReason: ''
    })
  },
  cancelOrder() {
    // 取消工单
    let url = _config.url.cancel_order.replace('{id}', this.data.formId)
    let requestData = {
      cancelReason: this.data.cancelReason
    }
    _fetch.post(url, requestData).then(() => {
      wx.showToast({
        title: '操作成功',
        icon: 'none'
      })
      this.getDetail(this.data.formId)
      this.getOrderlog(this.data.formId)
      this.getProgress(this.data.formId)
      this.closeCancel()
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  tabPermsButton(e) {
    // 详情按钮
    let command = e.currentTarget.dataset.btype
    switch (command) {
      case 'accept': // 受理工单
        this.tabAR(command);
        break;
      case 'refuse': // 拒绝工单
        this.tabAR(command);
        break;
      case 'assignForm': // 指派人员
        wx.navigateTo({
          url: `../appointMember/index?type=1&formid=${this.data.formId}&teamid=${this.data.teamId}`
        })
        break;
      case 'transferForm': // 转派团队 2期
        wx.navigateTo({
          url: `../appointMember/index?type=2&formid=${this.data.formId}`
        })
        break;
      case 'grabForm': // 抢单
        this.tapARBOrder(command);
        break;
      case 'receiveForm': // 接受工单
        this.tapARBOrder(command);
        break;
      case 'refuseForm': // 拒绝工单
        this.tapARBOrder(command);
        break;
      case 'startService': // 开始服务
        this.tapService(command);
        break;
      case 'applyException': // 申请异常
        this.setData({
          applyShow: !this.data.applyShow
        })
        break;
      case 'writeProgress': // 填写进度
        let reportid = '',
          curIndex = null,
          flag = true
        console.log(this.data.serve.serveFlow)
        if (this.data.serve.serveFlow.length > 0) {
          if (this.data.serve.serveFlow.length === 1) {
            reportid = this.data.serve.serveFlow[0].formReportId
            curIndex = 0
          }
          this.data.serve.serveFlow.map((i, idx) => {
            if (i.isCurrent) {
              flag = false
              curIndex = idx
            }
          })
          if (flag) {
            reportid = this.data.serve.serveFlow[0].formReportId
            curIndex = null
          } else {
            reportid = this.data.serve.serveFlow[curIndex].formReportId
          }
        }
        wx.navigateTo({
          url: `../progress/index?formid=${this.data.formId}&id=${reportid}&list=${JSON.stringify(this.data.serve.serveFlow)}&curidx=${curIndex}`
        })
        break;
      case 'completeService': // 完成服务
        this.tapService(command);
        break;
      case 'formMessage': // 工单留言 2期
        // this.tapARBOrder(command);
        break;
      case 'cancelForm': // 取消工单 2期
        this.setData({
          cancelShow: true
        })
        break;
      case 'assessForm': // 评价工单 2期
        // this.tapARBOrder(command);
        break;
      case 'agreeApply': // 同意
        this.setData({
          dealShow: !this.data.dealShow
        })
        break;
      case 'rejectApply': // 驳回
        this.setData({
          dealShow: !this.data.dealShow
        })
        break;
    }
  },
  sendFormId(e) {
    console.log(e)
    if (e.detail.target.dataset.btype !== 'writeProgress' && e.detail.target.dataset.btype !== 'applyException' && e.detail.target.dataset.btype !== 'cancelForm' && e.detail.target.dataset.btype !== 'agreeApply' && e.detail.target.dataset.btype !== 'rejectApply') {
      let formIds = [e.detail.formId]
      _fetch.post(_config.url.send_form_id, formIds).then(() => {}).catch(error => {
        wx.showToast({
          title: error.smg,
          icon: 'none',
        });
      })
    }
  },
  sendFormIds(e) {
    console.log(e)
    let formIds = [e.detail.formId]
    _fetch.post(_config.url.send_form_id, formIds).then(() => {}).catch(error => {
      wx.showToast({
        title: error.smg,
        icon: 'none',
      });
    })
  },
  inputApplyReason(e) {
    this.setData({
      applyDesc: e.detail.value
    })
  },
  inputCancelReason(e) {
    this.setData({
      cancelReason: e.detail.value
    })
  },
  applyException() {
    // 申请异常
    if (this.data.applyDesc == '' || this.data.applyDesc == null || this.data.applyDesc == undefined) {
      wx.showToast({
        title: '请输入原因',
        icon: 'none'
      })
      return
    }
    let url = _config.url.apply_err.replace('{formId}', this.data.formId)
    let requestData = {
      abnormalType: Number(this.data.checkRadio),
      reason: this.data.applyDesc
    }
    _fetch.put(url, requestData).then(() => {
      wx.showToast({
        title: '操作成功',
        icon: 'none'
      })
      this.closeDialog()
      this.getDetail(this.data.formId)
      this.getOrderlog(this.data.formId)
      this.getProgress(this.data.formId)
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  changeRadio(e) {
    // 更改选项
    if (e.currentTarget.dataset.kvalue) {
      this.setData({
        checkRadio: e.currentTarget.dataset.kvalue
      })
    }
  },
  closeDialog() {
    // 关闭申请
    this.setData({
      checkRadio: '1',
      applyShow: !this.data.applyShow,
      applyDesc: ''
    })
  },
  refuseAgreeApply(e) {
    // 异常处理
    let type = e.currentTarget.dataset.ttype
    let requestData = {
      abnormalType: this.data.cancelInfo.event.indexOf('申请改派') > -1 ? 2 : 1,
      dealStatus: type === 'rejectApply' ? 0 : 1,
      formAbnormalIds: [this.data.formAbId]
    }
    _fetch.put(_config.url.deal_err, requestData).then(() => {
      wx.showToast({
        title: '操作成功',
        icon: 'none'
      })
      this.closeDeal()
      this.getDetail(this.data.formId)
      this.getOrderlog(this.data.formId)
      this.getProgress(this.data.formId)
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  closeDeal() {
    // 关闭处理
    this.setData({
      dealShow: false
    })
  },
  toProgress(e) {
    // 前往进度详情
    if (e.currentTarget.dataset.flowlist && e.currentTarget.dataset.reportid) {
      let list = []
      if (e.currentTarget.dataset.flowlist) {
        list = JSON.stringify(e.currentTarget.dataset.flowlist)
      } else {
        list = JSON.stringify([])
      }
      wx.navigateTo({
        url: `../progress/index?formid=${this.data.formId}&id=${e.currentTarget.dataset.reportid}&list=${list}`
      })
    }
  }
})